package com.yyfax.pay.depository.controller.api;

import javax.annotation.Resource;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.yyfax.framework.common.Log;
import com.yyfax.framework.common.OpResponse;
import com.yyfax.pay.common.annotation.CheckSign;
import com.yyfax.pay.common.enums.FuiouDepositStateEnum;
import com.yyfax.pay.common.model.to.YYPayApiReq2;
import com.yyfax.pay.depository.domain.FuiouCharge;
import com.yyfax.pay.depository.service.inner.ChargeInnerService;
import com.yyfax.pay.depository.vo.FuiouChargeVO;
import com.yyfax.pay.vo.depository.ChargeProtocolSignRechargeReq;
import com.yyfax.pay.vo.depository.ChargeProtocolSignRechargeRsp;

/**
 * 充值入口
 * 
 * @author buyi
 * @date 2018-06-20 11:14:12
 * @since v2.2.2
 */
@RestController
public class ChargeApiController {
	private Logger logger = LoggerFactory.getLogger(getClass());

	@Resource
	private ChargeInnerService chargeInnerService;

	/**
	 * 协议充值<br>
	 * 
	 * <pre>
	 * 如果跟富友商务服务制定的规则不同，该接口有不同的业务
	 * 1.如果制定规则是下发验证码短信，则该接口代表发短信。
	 * 2.如果制定规则是不下发验证码短信，则该接口代表协议充值，返回结果代表交易结果。
	 * 
	 * 目前是采用方案2。如果要修改成方案1，需要调整接口，並且调整业务逻辑
	 * </pre>
	 * 
	 * @author buyi
	 * @date 2018-06-20 11:11:33
	 * @since v2.2.2
	 * @param req
	 * @return
	 * @throws Exception
	 */
	@CheckSign
	@PostMapping("/api/fuiou/charge/protocol/sign_recharge")
	public OpResponse protocolSignRecharge(@RequestBody @Valid YYPayApiReq2<ChargeProtocolSignRechargeReq> req) throws Exception {
		// 校验业务参数
		req.getParams().validParams();
		
		OpResponse opResponse = new OpResponse();

		FuiouChargeVO fuiouChargeVO = chargeInnerService.saveCharge(req.getMerchantCode(), req.getParams());
		FuiouCharge fuiouCharge = fuiouChargeVO.getPo();
		
		// 奇葩的上游系统，非要封装busiId响应参数
		ChargeProtocolSignRechargeRsp content = new ChargeProtocolSignRechargeRsp();
		content.setBusiId(fuiouCharge.getBusiId());

		if (!FuiouDepositStateEnum.INI.isValue(fuiouCharge.getState())) {
			// 协议充值，原来该接口是发送短信接口。因为协议绑定修改该接口规则，则该接口即表示订单结果，可以直接返回响应结果。如果是短信发送接口，则发送短信异常
			logger.info(Log.op("ChargeApiController.protocolSignRecharge").msg("协议充值已经出结果，直接返回支付结果")
					.kv("busiId", fuiouChargeVO.getPo().getBusiId()).toString());
			
			opResponse.setCode(fuiouCharge.getRspCode());
			opResponse.setDisplay(fuiouCharge.getRspMsg());
			opResponse.setContent(content);
			
			return opResponse;
		}

		FuiouCharge fuiouChargeNew = chargeInnerService.doProtocolSignRecharge(fuiouCharge);

		opResponse.setCode(fuiouChargeNew.getRspCode());
		opResponse.setDisplay(fuiouChargeNew.getRspMsg());
		opResponse.setContent(content);

		return opResponse;
	}
}
